<template>
  <div class="repair-task-container">
    <!-- 头部及筛选区域（蓝色背景） -->
    <div class="top-section">
      <!-- 重新设计的搜索区域 -->
      <div class="search-container">
        <div class="search-box">
          <input 
            ref="searchInput"
            class="search-input" 
            type="text" 
            placeholder="输入维修单号、方式或日期搜索" 
            v-model="searchValue"
            @keyup.enter="searchTasks"
            @focus="isSearchFocused = true"
            @blur="isSearchFocused = false"
          />
          <!-- 搜索按钮组：搜索 + 清除 -->
          <div class="search-btn-group">
            <button class="search-button" @click="searchTasks">
              <i class="search-icon">🔍</i>
            </button>
            <!-- 搜索内容不为空时显示清除按钮 -->
            <button 
              class="clear-button" 
              @click="clearSearch"
              v-if="searchValue.trim()"
            >
              <i class="clear-icon">×</i>
            </button>
          </div>
        </div>
        <!-- 搜索结果提示 -->
        <div class="search-result-hint" v-if="searchValue">
          搜索 "{{ searchValue }}"，找到 {{ filteredTaskList.length }} 条结果
        </div>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-area">
        <span class="total-text">共{{ filteredTaskList.length }}条</span>
        
        <!-- 状态筛选 -->
        <div class="filter-item">
          <span class="filter-label">状态</span>
          <div class="custom-select" @click="toggleStatusPopup">
            <span class="select-text">{{ selectedStatus }}</span>
            <img class="arrow-icon" src="/static/arrow-down.png" alt="下拉箭头" />
          </div>
        </div>
        
        <!-- 维修方式筛选 -->
        <div class="filter-item">
          <span class="filter-label">维修方式</span>
          <div class="custom-select" @click="toggleRepairWayPopup">
            <span class="select-text">{{ selectedRepairWay }}</span>
            <img class="arrow-icon" src="/static/arrow-down.png" alt="下拉箭头" />
          </div>
        </div>
        
        <!-- 日期筛选 -->
        <div class="filter-item date-item">
          <div class="date-label-container" @click="openDatePicker">
            <img class="time-icon" src="/static/time.png" alt="时间" />
            <span class="filter-label">{{ selectedDate || '日期' }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 维修任务列表：向上移动并部分嵌入蓝色头部 -->
    <div class="task-list">
      <!-- 任务项 -->
      <div 
        class="task-item" 
        v-for="(task, index) in filteredTaskList" 
        :key="'task-' + task.sn"
        :style="{ marginTop: index === 0? '0' : '24rpx' }"
      >
        <div class="task-top">
          <span class="task-sn">维修单号: {{ task.sn }}</span>
          <span class="task-status" :class="{ 
            'status-processing': task.status === '进行中', 
            'status-completed': task.status === '已完成' 
          }">
            {{ task.status }}
          </span>
        </div>
        <div class="task-info">
          <span class="task-way">维修方式: {{ task.way }}</span>
          <span class="task-time">预约日期: {{ task.time }}</span>
          <button class="detail-btn" @click="handleDetail(task)">查看详情</button>
        </div>
      </div>
      
      <!-- 空状态提示：同步调整位置 -->
      <div class="empty-state" v-if="filteredTaskList.length === 0">
        <img class="empty-icon" src="/static/empty.png" alt="暂无数据" />
        <span>暂无符合条件的维修任务</span>
      </div>
    </div>

    <!-- 状态选择弹窗 -->
    <div 
      class="popup-mask" 
      v-if="showStatusPopup"
      @click="toggleStatusPopup"
    >
      <div class="popup-content" @click.stop>
        <div class="popup-title">选择状态</div>
        <div 
          class="popup-item" 
          v-for="option in statusOptions" 
          :key="option"
          @click="handleStatusChange(option)"
          :class="{ 'popup-item-active': selectedStatus === option }"
        >
          {{ option }}
        </div>
        <div class="popup-cancel" @click="toggleStatusPopup">取消</div>
      </div>
    </div>

    <!-- 维修方式选择弹窗 -->
    <div 
      class="popup-mask" 
      v-if="showRepairWayPopup"
      @click="toggleRepairWayPopup"
    >
      <div class="popup-content" @click.stop>
        <div class="popup-title">选择维修方式</div>
        <div 
          class="popup-item" 
          v-for="option in repairWayOptions" 
          :key="option"
          @click="handleRepairWayChange(option)"
          :class="{ 'popup-item-active': selectedRepairWay === option }"
        >
          {{ option }}
        </div>
        <div class="popup-cancel" @click="toggleRepairWayPopup">取消</div>
      </div>
    </div>

    <!-- 日期选择器（触摸滑动版） -->
    <div 
      class="date-picker-mask" 
      v-if="showDatePicker"
      @click="closeDatePicker"
    >
      <div class="date-picker-content" @click.stop>
        <div class="date-picker-header">
          <span class="date-picker-cancel" @click="closeDatePicker">取消</span>
          <span class="date-picker-title">选择日期</span>
          <span class="date-picker-confirm" @click="confirmDate">确定</span>
        </div>
        <div class="date-picker-body">
          <!-- 选中线 -->
          <div class="picker-selected-line"></div>
          <!-- 日期选择器主体 -->
          <div class="picker-view">
            <!-- 年份列 -->
            <div class="picker-view-column" 
                 @touchstart="startDatePick($event, 0)" 
                 @touchmove="moveDatePick($event, 0)" 
                 @touchend="endDatePick(0)"
                 :style="{ transform: `translateY(${yearOffset}px)` }">
              <div class="picker-item" 
                   v-for="(year, index) in years" 
                   :key="year" 
                   :data-index="index"
                   :class="{ 'picker-item-active': index === currentIndex[0] }">
                {{ year }}年
              </div>
            </div>
            <!-- 月份列 -->
            <div class="picker-view-column" 
                 @touchstart="startDatePick($event, 1)" 
                 @touchmove="moveDatePick($event, 1)" 
                 @touchend="endDatePick(1)"
                 :style="{ transform: `translateY(${monthOffset}px)` }">
              <div class="picker-item" 
                   v-for="(month, index) in months" 
                   :key="month" 
                   :data-index="index"
                   :class="{ 'picker-item-active': index === currentIndex[1] }">
                {{ month }}月
              </div>
            </div>
            <!-- 日期列 -->
            <div class="picker-view-column" 
                 @touchstart="startDatePick($event, 2)" 
                 @touchmove="moveDatePick($event, 2)" 
                 @touchend="endDatePick(2)"
                 :style="{ transform: `translateY(${dayOffset}px)` }">
              <div class="picker-item" 
                   v-for="(day, index) in days" 
                   :key="day" 
                   :data-index="index"
                   :class="{ 'picker-item-active': index === currentIndex[2] }">
                {{ day }}日
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'RepairTask',
  data() {
    return {
      // 搜索值
      searchValue: '',
      // 搜索框焦点状态
      isSearchFocused: false,

      // 弹窗控制
      showStatusPopup: false,
      showRepairWayPopup: false,
      showDatePicker: false,

      // 筛选选项
      statusOptions: ['全部', '进行中', '已完成'],
      repairWayOptions: ['全部', '到店维修', '上门取车'],

      // 选中值
      selectedStatus: '全部',
      selectedRepairWay: '全部',
      selectedDate: '',

      // 日期选择器数据
      years: [],
      months: Array.from({ length: 12 }, (_, i) => i + 1),
      days: [],
      currentIndex: [5, new Date().getMonth(), new Date().getDate() - 1],
      
      // 日期选择触摸相关
      startY: 0,
      currentOffset: [0, 0, 0],
      yearOffset: 0,
      monthOffset: 0,
      dayOffset: 0,
      isDragging: false,
      activeColumn: -1,
      itemHeight: 80,
      bounceHeight: 50,
      
      // 任务数据
      taskList: [
        {
          sn: 'RX20230318001',
          status: '进行中',
          way: '到店维修',
          time: '2023-03-18 11:00'
        },
        {
          sn: 'RX20230318002',
          status: '已完成',
          way: '上门取车',
          time: '2023-03-18 09:30'
        },
        {
          sn: 'RX20230317001',
          status: '进行中',
          way: '上门取车',
          time: '2023-03-17 15:45'
        },
        {
          sn: 'RX20230319001',
          status: '已完成',
          way: '到店维修',
          time: '2023-03-19 14:20'
        }
      ]
    };
  },
  computed: {
    filteredTaskList() {
      const { selectedStatus, selectedRepairWay, selectedDate, searchValue, taskList } = this;
      return taskList.filter(task => {
        // 状态筛选
        if (selectedStatus!== '全部' && task.status!== selectedStatus) return false;
        
        // 维修方式筛选
        if (selectedRepairWay!== '全部' && task.way!== selectedRepairWay) return false;
        
        // 日期筛选
        if (selectedDate &&!task.time.startsWith(selectedDate)) return false;
        
        // 搜索筛选
        if (searchValue) {
          const lowerSearch = searchValue.toLowerCase();
          return (
            task.sn.toLowerCase().includes(lowerSearch) ||
            task.way.toLowerCase().includes(lowerSearch) ||
            task.time.toLowerCase().includes(lowerSearch) ||
            task.status.toLowerCase().includes(lowerSearch)
          );
        }
        
        return true;
      });
    }
  },
  mounted() {
    this.initDateData();
    this.calculateOffsets();
  },
  methods: {
    // 搜索功能实现
    searchTasks() {
      if (this.searchValue.trim() === '') {
        // 清空搜索时重置筛选条件
        this.selectedStatus = '全部';
        this.selectedRepairWay = '全部';
        this.selectedDate = '';
      }
    },
    
    // 清空搜索
    clearSearch() {
      this.searchValue = '';
      this.searchTasks();
      // 清空后让输入框重新获取焦点
      this.$nextTick(() => {
        this.$refs.searchInput?.focus();
      });
    },
    
    initDateData() {
      const currentYear = new Date().getFullYear();
      // 生成年份数据（当前年±5年）
      this.years = Array.from({ length: 11 }, (_, i) => currentYear - 5 + i);
      this.updateDays();
    },

    updateDays() {
      const selectedYear = this.years[this.currentIndex[0]];
      const selectedMonth = this.months[this.currentIndex[1]];
      // 获取当月天数
      const dayCount = new Date(selectedYear, selectedMonth, 0).getDate();
      
      this.days = Array.from({ length: dayCount }, (_, i) => i + 1);
      
      // 确保日期索引有效
      if (this.currentIndex[2] >= this.days.length) {
        this.currentIndex[2] = this.days.length - 1;
      }
      
      this.calculateOffsets();
    },

    calculateOffsets() {
      // 计算每个列的偏移量，使选中项居中
      const centerBase = this.itemHeight * 2;
      this.yearOffset = centerBase - this.currentIndex[0] * this.itemHeight;
      this.monthOffset = centerBase - this.currentIndex[1] * this.itemHeight;
      this.dayOffset = centerBase - this.currentIndex[2] * this.itemHeight;
      
      this.currentOffset = [this.yearOffset, this.monthOffset, this.dayOffset];
    },

    // 打开日期选择器
    openDatePicker() {
      this.showDatePicker = true;
      this.$nextTick(() => {
        this.calculateOffsets();
      });
    },
    
    // 关闭日期选择器
    closeDatePicker() {
      this.showDatePicker = false;
      this.isDragging = false;
      this.activeColumn = -1;
    },

    // 清除已选日期
    clearSelectedDate() {
      this.selectedDate = '';
    },

    // 日期选择触摸事件 - 开始
    startDatePick(e, column) {
      this.isDragging = true;
      this.activeColumn = column;
      this.startY = e.touches[0].clientY;
    },

    // 日期选择触摸事件 - 移动
    moveDatePick(e, column) {
      if (!this.isDragging || this.activeColumn!== column) return;
      
      const moveY = e.touches[0].clientY;
      const diffY = moveY - this.startY;
      const targetColumnLength = column === 0? this.years.length : 
                                column === 1? this.months.length : this.days.length;

      // 边界限制
      const maxOffset = this.itemHeight * 2 + this.bounceHeight;
      const minOffset = this.itemHeight * (2 - targetColumnLength) - this.bounceHeight;

      if (column === 0) {
        this.yearOffset = Math.max(minOffset, Math.min(maxOffset, this.currentOffset[0] + diffY));
      } else if (column === 1) {
        this.monthOffset = Math.max(minOffset, Math.min(maxOffset, this.currentOffset[1] + diffY));
      } else {
        this.dayOffset = Math.max(minOffset, Math.min(maxOffset, this.currentOffset[2] + diffY));
      }
    },

    // 日期选择触摸事件 - 结束
    endDatePick(column) {
      if (!this.isDragging || this.activeColumn!== column) return;
      
      this.isDragging = false;
      const centerBase = this.itemHeight * 2;
      let newIndex = 0;
      const targetColumnLength = column === 0? this.years.length : 
                                column === 1? this.months.length : this.days.length;

      // 计算最终选中的索引
      if (column === 0) {
        newIndex = Math.round((centerBase - this.yearOffset) / this.itemHeight);
        newIndex = Math.max(0, Math.min(targetColumnLength - 1, newIndex));
        this.currentIndex[0] = newIndex;
      } else if (column === 1) {
        newIndex = Math.round((centerBase - this.monthOffset) / this.itemHeight);
        newIndex = Math.max(0, Math.min(targetColumnLength - 1, newIndex));
        this.currentIndex[1] = newIndex;
        this.updateDays(); // 月份变化时更新日期
        this.activeColumn = -1;
        return;
      } else {
        newIndex = Math.round((centerBase - this.dayOffset) / this.itemHeight);
        newIndex = Math.max(0, Math.min(targetColumnLength - 1, newIndex));
        this.currentIndex[2] = newIndex;
      }
      
      this.calculateOffsets();
      this.activeColumn = -1;
    },

    // 确认日期选择
    confirmDate() {
      const year = this.years[this.currentIndex[0]];
      const month = this.months[this.currentIndex[1]].toString().padStart(2, '0');
      const day = this.days[this.currentIndex[2]].toString().padStart(2, '0');

      this.selectedDate = `${year}-${month}-${day}`;
      this.showDatePicker = false;
    },

    // 状态弹窗控制
    toggleStatusPopup() {
      this.showStatusPopup =!this.showStatusPopup;
    },

    // 维修方式弹窗控制
    toggleRepairWayPopup() {
      this.showRepairWayPopup =!this.showRepairWayPopup;
    },

    // 状态筛选处理
    handleStatusChange(val) {
      this.selectedStatus = val;
      this.showStatusPopup = false;
    },

    // 维修方式筛选处理
    handleRepairWayChange(val) {
      this.selectedRepairWay = val;
      this.showRepairWayPopup = false;
    },

    // 查看详情
    handleDetail(task) {
      console.log('查看详情:', task);
      // 这里可以添加跳转到详情页的逻辑
    }
  }
};
</script>

<style scoped>
/* 基础样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.repair-task-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

/* 顶部蓝色区域 */
.top-section {
  background-color: #2563eb;
  padding: 20rpx;
  padding-top: 40rpx;
  padding-bottom: 80rpx; /* 增加底部 padding 为任务列表预留嵌入空间 */
  margin-left: -16rpx;
  margin-right: -17rpx;
  position: relative;
  z-index: 10;
  height: 420rpx;
}

/* 搜索区域 */
.search-container {
  margin: 0 20rpx 20rpx;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  border-radius: 60rpx;
  padding: 8rpx 10rpx;
  box-shadow: 0 4rpx 8rpx rgba(0,0,0,0.04);
  border: 1rpx solid #e6efff;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
  background: transparent;
  padding: 16rpx 20rpx;
  border: none;
  outline: none;
  min-width: 0;
}

/* 焦点状态样式增强 */
.search-input:focus {
  caret-color: #2563eb; /* 光标颜色与主题一致 */
}

.search-input::placeholder {
  color: #999999;
  font-size: 28rpx;
}

/* 搜索按钮组样式 */
.search-btn-group {
  display: flex;
  align-items: center;
}

.search-button {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  color: white;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8rpx;
  cursor: pointer;
  transition: background-color 0.2s;
}

.search-button:active {
  background-color: #1d4ed8;
}

/* 清除按钮样式 */
.clear-button {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #f0f0f0;
  color: #666;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8rpx;
  cursor: pointer;
  font-size: 24rpx;
  transition: all 0.2s;
}

.clear-button:active {
  background-color: #e0e0e0;
  color: #333;
}

.search-icon {
  font-size: 30rpx;
}

.search-result-hint {
  color: rgba(255, 255, 255, 0.8);
  font-size: 24rpx;
  padding: 10rpx 20rpx;
  text-align: left;
}

/* 筛选区域 */
.filter-area {
  display: flex;
  align-items: flex-start;
  justify-content: space-around;
  padding: 10rpx 0;
  flex-wrap: wrap;
}

.total-text {
  font-size: 28rpx;
  color: #ffffff;
  margin-top: 4rpx;
}

.filter-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 10rpx;
  position: relative;
}

.filter-label {
  font-size: 28rpx;
  color: #ffffff;
  margin-bottom: 6rpx;
  cursor: pointer;
}

.custom-select {
  display: flex;
  align-items: center;
  background-color: #0b48b5;
  color: #ffffff;
  border-radius: 16rpx;
  padding: 6rpx 16rpx;
  min-width: 120rpx;
  justify-content: space-between;
  cursor: pointer;
}

.select-text {
  font-size: 28rpx;
}

.arrow-icon {
  width: 24rpx;
  height: 24rpx;
}

.date-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.date-label-container {
  display: flex;
  align-items: center;
  margin-bottom: 6rpx;
  cursor: pointer;
}

.time-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 8rpx;
}

/* 任务列表：核心调整 - 向上移动并部分嵌入蓝色背景 */
.task-list {
  flex: 1;
  background-color: transparent; /* 设为透明，露出底层背景色 */
  padding: 0 24rpx;
  margin-top: -100rpx; /* 负margin向上移动，嵌入蓝色区域 */
  overflow-y: auto;
  position: relative;
  z-index: 20; /* 确保列表在头部上方显示 */
}

.task-item {
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  transition: transform 0.2s ease;
  /* 顶部任务项有圆角，增强嵌入感 */
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
}

.task-item:active {
  transform: scale(0.99);
}

.task-top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.task-sn {
  font-size: 30rpx;
  color: #1f2937;
  font-weight: 500;
}

.task-status {
  font-size: 28rpx;
  padding: 4rpx 16rpx;
  border-radius: 16rpx;
  font-weight: 500;
}

.status-processing {
  color: #165dff;
  background-color: #eff6ff;
}

.status-completed {
  color: #00b42a;
  background-color: #f0fdf4;
}

.task-info {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.task-way, .task-time {
  font-size: 28rpx;
  color: #6b7280;
}

.detail-btn {
  background-color: #2563eb;
  color: #ffffff;
  font-size: 24rpx;
  border-radius: 30rpx;
  padding: 10rpx 26rpx;
  border: none;
  margin-left: auto;
  margin-top: 10rpx;
  cursor: pointer;
  transition: background-color 0.2s;
}

.detail-btn:active {
  background-color: #1d4ed8;
}

/* 空状态提示：同步上移 */
.empty-state {
  text-align: center;
  padding: 100rpx 0 40rpx;
  color: #9ca3af;
  font-size: 28rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20rpx;
  margin-top: 20rpx;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  opacity: 0.5;
}

/* 弹窗样式 */
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: flex-end;
  z-index: 999;
}

.popup-content {
  width: 100%;
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  padding-bottom: 30rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.popup-title {
  font-size: 32rpx;
  text-align: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
  color: #1f2937;
}

.popup-item {
  font-size: 28rpx;
  padding: 20rpx;
  text-align: center;
  border-bottom: 1rpx solid #eee;
  color: #374151;
  cursor: pointer;
  transition: background-color 0.2s;
}

.popup-item:active {
  background-color: #f3f4f6;
}

.popup-item-active {
  color: #2563eb;
  font-weight: 500;
}

.popup-cancel {
  font-size: 28rpx;
  text-align: center;
  padding: 20rpx;
  margin-top: 10rpx;
  color: #ff4d4f;
  cursor: pointer;
}

/* 日期选择器 */
.date-picker-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: flex-end;
  z-index: 999;
}

.date-picker-content {
  width: 100%;
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
}

.date-picker-header {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.date-picker-cancel, .date-picker-confirm {
  font-size: 28rpx;
  padding: 0 20rpx;
  cursor: pointer;
}

.date-picker-cancel {
  color: #666;
}

.date-picker-confirm {
  color: #2563eb;
  font-weight: 500;
}

.date-picker-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #1f2937;
}

.date-picker-body {
  height: 400rpx;
  position: relative;
  overflow: hidden;
}

.picker-view {
  width: 100%;
  height: 100%;
  display: flex;
  padding: 100rpx 0;
  box-sizing: content-box;
}

.picker-view-column {
  flex: 1;
  overflow: hidden;
  position: relative;
  transition: transform 0.1s ease-out;
}

.picker-item {
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-size: 28rpx;
  color: #9ca3af;
  transition: color 0.2s;
}

.picker-item-active {
  color: #1f2937;
  font-size: 32rpx;
  font-weight: 500;
}

/* 选中线样式 */
.picker-selected-line {
  position: absolute;
  top: 50%;
  left: 0;
  height: 80rpx;
  margin-top: -40rpx;
  pointer-events: none;
  border-top: 1rpx solid #eee;
  border-bottom: 1rpx solid #eee;
  background-color: rgba(255, 255, 255, 0.6);
  box-sizing: border-box;
  z-index: 10;
}
</style>
